package com.tweetgraph.util;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.tweetgraph.domain.BasicQuery;

public class TGUtil {

	/**
	 * 
	 * @param query
	 */
	public static void saveQuery(BasicQuery query) {

		if(query != null){
			Key key = KeyFactory.createKey("QueryResult", query.getHashTag());
			
			/*
			 * Check if there is an entity with the same #hashtag already exists in the db
			 */
			DatastoreService datastore =  DatastoreServiceFactory.getDatastoreService();
			BasicQuery existingQuery = null;
			Entity queryEntity = null;
			
			try{
				Entity existEnt = datastore.get(key);
				existingQuery = BasicQuery.getInstance(existEnt);
			}catch(EntityNotFoundException e){
				//do nothing - create a new Entity and insert
			}

			
			/*
			 * Get the entity object to save by adding new keywords to the 
			 * existing object or create a new object if there is no existing obj
			 */
			if(existingQuery != null){
				existingQuery.addAllKeyWords(query.getKeywordSet());
				existingQuery.setCountOther(query.isCountOther());
				existingQuery.setNeedToUpdateResults(false);
				
				queryEntity = existingQuery.getEntity();
			}else{
				queryEntity = query.getEntity();
			}
			
			datastore.put(queryEntity);

			//			
//			long id = System.currentTimeMillis();
//			Key childK = KeyFactory.createKey(key, "tweet",""+id);
//			Entity ent1 = new Entity(childK);
////			ent1.setProperty("type", "tweet");
//			
//			ent1.setProperty("text","THIS IS THE TWEET TExT");
//			ent1.setProperty("user", "The Tweet User");
//			ent1.setProperty("id", ""+id);
//			
//			datastore.put(ent1);
		}

	}
	
	
	/**
	 * 
	 * @param hashTag
	 */
	public static void printQueryDetails(String hashTag){
		Key key = KeyFactory.createKey("QueryResult", hashTag);
//		Query query = new Query(key);
//		Query query = new Query("QueryResult");
//		query.addFilter("type",FilterOperator.EQUAL,"basic");
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		try{
			Entity result = datastore.get(key);
			System.out.println("result>>>" + result);
//			Query query = new Query("tweet",key);
////			query.addFilter("type", FilterOperator.EQUAL, "tweet");
//			List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(500));
//			System.out.println("THeresuls>>" + results.toString());
			
		}catch(EntityNotFoundException e){
			e.printStackTrace();
		}
		
	}

}
